package vn.lumi.smarthome.ui.base;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

import vn.lumi.smarthome.ActivityHelper;
import vn.lumi.smarthome.Config;
import vn.lumi.smarthome.R;
import vn.lumi.smarthome.io.database.DatabaseHelper;
import vn.lumi.smarthome.io.database.TBL_Floor;
import vn.lumi.smarthome.io.database.TBL_Room;
import vn.lumi.smarthome.provider.SmartHomeProvider;
import vn.lumi.smarthome.service.ReceiveDataThread;
import vn.lumi.smarthome.service.SmartHomeService;
import vn.lumi.smarthome.service.TransmitThread;
import vn.lumi.smarthome.service.VibrateThread;
import vn.lumi.smarthome.ui.base.MainFragment.OnTabSelectedListener;
import vn.lumi.smarthome.ui.base.MainFragment.TABS;
import vn.lumi.smarthome.ui.base.MenuFragment.OnFloorRoomClickListener;
import vn.lumi.smarthome.ui.login.LoginActivity;
import vn.lumi.smarthome.ui.setting.SettingFragment.SettingFragmentOnListenerInterface;

import vn.lumi.smarthome.ulti.LogUltis;
import vn.lumi.smarthome.ulti.Preference;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import com.slidingmenu.lib.SlidingMenu;
import com.slidingmenu.lib.app.SlidingFragmentActivity;

public class MainActivity extends SlidingFragmentActivity implements
		OnFloorRoomClickListener, OnTabSelectedListener,
		SettingFragmentOnListenerInterface {
	private static final String TAG = "MainActivity";

	private static final int TAB_DEVICE = 0;
	private static final int TAB_SCENE = 1;
	int mCurrentTab = TAB_DEVICE;
	private static final String KEY_CURRENT_TAB = "key_current_tab";

	// Cac bien luu gia tri room_id vs floor_id dang duoc chon
	public static int mRoomId = 0; // Mac dinh phong khong bao gio co mRoomID =0
	public static int mFloorId;

	// hay thiet bi
	public static String nameRoom = null;
	public static String nameFloor = null;

	SlidingMenu slidingMenu;

	boolean isPressableEditScene = true; // Luc dau true de co the bam edit
	boolean isEnterAdddScene = false; // Kiem tra xem luc dau nhay vao fragment
										// canh
	boolean isEnterEditScene = false;
	boolean isAnotherActivity = false;
	private static boolean isTabletTab = false;

	public static boolean isTabletTab() {
		return isTabletTab;
	}

	// Socket
	Socket socket = null;
	InputStream is;
	OutputStream os;
	boolean isUserRestart = false;

	public static final int ADD_SCENE_REQUEST = 1;
	public static final int EDIT_SCENE_REQUEST = 2;
	public static final int SETTING_REQUEST = 3;
	public static final int ANOTHER_REQUEST = 4; // Danh cho cac activity khac
													// mac dinh vao device
													// fragment
	public static final String STRING_ANOTHER_REQUEST = "another_request";
	public static final String CONFIGING_LANGUAGE = "configing language";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		ActivityHelper.initialize(this);
		super.onCreate(savedInstanceState);
		// Chon ngon ngu
		Config.configLanguage(getBaseContext(),
				Preference.getLanguage(getApplicationContext()));

		if (savedInstanceState != null) {
			mCurrentTab = savedInstanceState.getInt(KEY_CURRENT_TAB);
		}

		Intent intent = getIntent();
		boolean isUserRestart = intent.getBooleanExtra("finish", false);
		if (isUserRestart) {
			this.finish();
			Intent i = new Intent(MainActivity.this, LoginActivity.class);
			startActivity(i);
			return;
		}

		setContentView(R.layout.activity_main);

		// Neu la may tinh bang
		if (findViewById(R.id.activity_main_menu_content) != null) {
			setupMenuForTable();
			isTabletTab = true;
			setBehindContentView(R.layout.activity_main_behind);
			slidingMenu = getSlidingMenu();
			slidingMenu.setSlidingEnabled(false);
			// actionbar.setDisplayHomeAsUpEnabled(false);
			slidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_NONE); // khong cho swipe canh man
																		// hinh
			getSlidingMenu().showMenu(true);
		}

		// Neu la dien thoai binh thuong
		else {
			setBehindContentView(R.layout.activity_main_behind);

			// Set listener cho button acbar_home
			// acbar_home.setOnClickListener(this);
			slidingMenu = getSlidingMenu();
			setupSlidingMenu(slidingMenu);
			setupMenuForMobile();
		}
		setHomeScreen(false);

		// Bind Service to Content Provider
		Context mContext = getApplicationContext();
		mContext.getContentResolver().delete(
				SmartHomeProvider.BIND_SERVICE_URI, null, null);
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		// changeLanguage();
		Config.isVibrate = Preference.getVibrate(this);
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putInt(KEY_CURRENT_TAB, mCurrentTab);
	}

	private void setupSlidingMenu(SlidingMenu slideMenu) {
		SlidingMenu slidingMenu = slideMenu;
		slidingMenu.setBehindOffsetRes(R.dimen.sliding_behind_offset);
		slidingMenu.setShadowWidthRes(R.dimen.sliding_shadow_width);
		slidingMenu.setFadeDegree(1.0f);
	}

	// -----------------------------Actionbar------------------
	// private void setupActionBar() {
	// btn_switch = (Button) findViewById(R.id.layout_actionbar_switch);
	// btn_switch.setOnClickListener(this);
	// acbar_home = (ImageButton) findViewById(R.id.layout_actionbar_home);
	// btn_turnAlloff = (Button) findViewById(R.id.layout_actionbar_turnoff);
	// btn_turnAlloff.setOnClickListener(this);
	// btn_turnAllon = (Button) findViewById(R.id.layout_actionbar_turnon);
	// btn_turnAllon.setOnClickListener(this);
	// btn_addScene = (Button) findViewById(R.id.layout_actionbar_addScence);
	// btn_addScene.setOnClickListener(this);
	// btn_editScene = (Button) findViewById(R.id.layout_actionbar_editScence);
	// btn_editScene.setOnClickListener(this);
	// titleActionbar = (TextView) findViewById(R.id.layout_actionbar_title);
	//
	// }

	// /*
	// * (non-Javadoc)
	// *
	// * @see android.view.View.OnClickListener#onClick(android.view.View)
	// */
	// @Override
	// public void onClick(View v) {
	// // TODO Auto-generated method stub
	// if (Config.isVibrate)
	// new VibrateThread(getApplicationContext()).start();
	// switch (v.getId()) {
	// case R.id.layout_actionbar_home:
	// if (isPressableEditScene && !isTabletTab) { // Neu co the bam edit va khong phai la
	// // tablet
	// getSlidingMenu().showMenu(true);
	// }
	// break;
	// case R.id.layout_actionbar_switch:
	// if (isPressableEditScene) {
	// if (isDevice) {
	// setButtonToScence();
	// isDevice = false;
	// // Bao cho ben ViewPage biet de chuyen sang Fragment canh
	// switchMainFragment(isDevice);
	//
	// } else {
	// setButtonToDevice();
	// isDevice = true;
	// // Bao cho ben ViewPage biet de chuyen sang Fragment device
	// switchMainFragment(isDevice);
	// }
	// }
	// break;
	// case R.id.layout_actionbar_turnoff:
	// turnAllOffOnRoom(mRoomId);
	// break;
	// case R.id.layout_actionbar_turnon:
	// turnAllOnOnRoom(mRoomId);
	// break;
	// case R.id.layout_actionbar_addScence:
	// Intent intent = new Intent(this, AddSceneActivity.class);
	// intent.putExtra(AddSceneActivity.EXTRA_FLOOR_ID, mFloorId);
	// intent.putExtra(AddSceneActivity.EXTRA_ROOM_ID, mRoomId);
	// startActivityForResult(intent, ADD_SCENE_REQUEST);
	// break;
	// case R.id.layout_actionbar_editScence:
	// FragmentManager fragmentManager = getSupportFragmentManager();
	// FragmentTransaction transaction = fragmentManager
	// .beginTransaction();
	//
	// if (isPressableEditScene) {
	//
	// EditSceneFragment editFragment = EditSceneFragment.newInstance(
	// mFloorId, mRoomId);
	// transaction.replace(R.id.activity_main_content, editFragment,
	// "editScene").commit();
	// isPressableEditScene = false;
	// btn_editScene.setBackgroundResource(R.drawable.img_ok);
	// if (!isTabletTab) {
	// slidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_NONE);
	// }
	// } else {
	// setTitleActionbar(nameRoom + "-" + nameFloor);
	// MainFragment mainFragment = MainFragment.newInstance(mFloorId,
	// mRoomId, MainFragment.SCREEN_SCENE);
	// transaction.replace(R.id.activity_main_content, mainFragment,
	// "main").commit();
	// btn_editScene
	// .setBackgroundResource(R.drawable.img_editscene_selector);
	// if (isTabletTab) {
	// slidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_MARGIN);
	// }
	//
	// isPressableEditScene = true;
	//
	// }
	// break;
	// default:
	// break;
	// }
	// }

	// private void setButtonToScence() {
	// if (Preference.getLanguage(getApplicationContext()) == Config.LANGUAGE_VIETNAM) // Neu
	// // la
	// // ngon
	// // ngu
	// // Viet
	// // Nam
	// btn_switch.setBackgroundDrawable(getResources().getDrawable(
	// R.drawable.img_switch_canh));
	// else if (Preference.getLanguage(getApplicationContext()) == Config.LANGUAGE_ENGLISH) { // Neu
	// // la
	// // ngon
	// // ngu
	// // English
	// btn_switch.setBackgroundDrawable(getResources().getDrawable(
	// R.drawable.img_switch_canh_en));
	// }
	// btn_turnAlloff.setVisibility(View.GONE);
	// btn_turnAllon.setVisibility(View.GONE);
	// btn_addScene.setVisibility(View.VISIBLE);
	// btn_editScene.setVisibility(View.VISIBLE);
	// }
	//
	// private void setButtonToDevice() {
	// if (Preference.getLanguage(getApplicationContext()) == Config.LANGUAGE_VIETNAM) // Neu
	// // la
	// // ngon
	// // ngu
	// // Viet
	// // Nam
	// btn_switch.setBackgroundDrawable(getResources().getDrawable(
	// R.drawable.img_switch_dev));
	// else if (Preference.getLanguage(getApplicationContext()) == Config.LANGUAGE_ENGLISH) { // Neu
	// // la
	// // ngon
	// // ngu
	// // English
	// btn_switch.setBackgroundDrawable(getResources().getDrawable(
	// R.drawable.img_switch_dev_en));
	// }
	// btn_turnAlloff.setVisibility(View.VISIBLE);
	// btn_turnAllon.setVisibility(View.VISIBLE);
	// btn_addScene.setVisibility(View.GONE);
	// btn_editScene.setVisibility(View.GONE);
	// }

	private void setupMenuForTable() {
		MenuFragment menuFragment = new MenuFragment();
		getSupportFragmentManager().beginTransaction()
				.replace(R.id.activity_main_menu_content, menuFragment, "menu")
				.commit();

	}

	// ------------------------------------------------------------------
	private void setupMenuForMobile() {
		MenuFragment menuFragment = new MenuFragment();
		getSupportFragmentManager()
				.beginTransaction()
				.replace(R.id.activity_main_behind_content, menuFragment,
						"menu").commit();

	}

	private void setHomeScreen(boolean isSceneFragment) {

		Cursor cursor = null;

		// Truy van lay mFloorId va nameFloor
		String[] projectionFloor = new String[] { TBL_Floor._ID, TBL_Floor.NAME };
		cursor = getContentResolver().query(TBL_Floor.CONTENT_URI_FLOOR,
				projectionFloor, null, null, TBL_Floor._ID);
		cursor.moveToFirst();
		if (cursor.getCount() != 0) {
			mFloorId = cursor.getInt(cursor.getColumnIndex(TBL_Floor._ID));
			nameFloor = cursor.getString(cursor.getColumnIndex(TBL_Floor.NAME));
		}

		if (cursor != null) {
			cursor.close();
			cursor = null;
		}

		// Truy van de lay id cua Room va ten cua room
		String[] projectionRoom = new String[] { TBL_Room._ID, TBL_Room.NAME };
		String selection = DatabaseHelper.DB_TBL_ROOM + "." + TBL_Room.FLOOR_ID
				+ "=?";
		String[] selectionArgs = { mFloorId + "" };
		cursor = getContentResolver().query(TBL_Room.CONTENT_URI_ROOM,
				projectionRoom, selection, selectionArgs, TBL_Room._ID);
		cursor.moveToFirst();
		if (cursor.getCount() != 0) {
			mRoomId = cursor.getInt(cursor.getColumnIndex(TBL_Room._ID));
			nameRoom = cursor.getString(cursor.getColumnIndex(TBL_Room.NAME));
		}
		if (cursor != null) {
			cursor.close();
			cursor = null;
		}

		FragmentManager fragmentManager = getSupportFragmentManager();
		MainFragment mainFragment = (MainFragment) fragmentManager
				.findFragmentByTag("main");
		if (mainFragment == null) {
			if (isSceneFragment) {
				mainFragment = MainFragment.newInstance(mFloorId, mRoomId,
						MainFragment.SCREEN_SCENE, nameRoom, nameFloor);
				mainFragment.setButtonToScence();
			} else {
				mainFragment = MainFragment.newInstance(mFloorId, mRoomId,
						MainFragment.SCREEN_DEVICE, nameRoom, nameFloor);
				// mainFragment.setButtonToDevice();
			}
			FragmentTransaction transaction = getSupportFragmentManager()
					.beginTransaction();
			transaction.replace(R.id.activity_main_content, mainFragment,
					"main");
			transaction.commit();
		} else {
			mainFragment
					.onlyRefreshData(mFloorId, mRoomId, nameRoom, nameFloor);
			if (isSceneFragment)
				mainFragment.switchFragment(false);
			else
				mainFragment.switchFragment(true);

		}

	}

	/**
	 * @param isSceneFragment
	 *            : Chuyen sang SceneFragment neu gia tri nay bang true
	 * @param room_id
	 *            : id cua phong ma se hien thi ra o MainFragment
	 * 
	 *            Ham nay de tao lai MainFragment
	 */
	/*
	 * private void RecreatMainFragment(boolean isSceneFragment, int room_id) { Cursor cursor =
	 * null; mRoomId = room_id; // Truy van de lay id cua Room va Floor va ten cua room String[]
	 * projectionRoom = new String[] { TBL_Room.FLOOR_ID, TBL_Room.NAME }; String selectionRoom =
	 * TBL_Room._ID + "=?"; String[] selectionArgsRoom = { mRoomId + "" }; cursor =
	 * getContentResolver().query(TBL_Room.CONTENT_URI_ROOM, projectionRoom, selectionRoom,
	 * selectionArgsRoom, null); cursor.moveToFirst(); mFloorId =
	 * cursor.getInt(cursor.getColumnIndex(TBL_Room.FLOOR_ID)); nameRoom =
	 * cursor.getString(cursor.getColumnIndex(TBL_Room.NAME));
	 * 
	 * // Truy van de lay ten Floor if (cursor != null) { cursor.close(); cursor = null; } String[]
	 * projection2 = { TBL_Floor.NAME }; String selection = TBL_Floor._ID + "=?"; String[]
	 * selectionArgs = { mFloorId + "" }; cursor =
	 * getContentResolver().query(TBL_Floor.CONTENT_URI_FLOOR, projection2, selection,
	 * selectionArgs, null); cursor.moveToFirst(); nameFloor =
	 * cursor.getString(cursor.getColumnIndex(TBL_Floor.NAME)); if (cursor != null) {
	 * cursor.close(); cursor = null; }
	 * 
	 * FragmentManager fragmentManager = getSupportFragmentManager(); MainFragment mainFragment =
	 * (MainFragment) fragmentManager .findFragmentByTag("main"); if (mainFragment == null) { if
	 * (isSceneFragment) { mainFragment = MainFragment.newInstance(mFloorId, mRoomId,
	 * MainFragment.SCREEN_SCENE, nameRoom, nameFloor); // mainFragment.setButtonToScence(); } else
	 * { mainFragment = MainFragment.newInstance(mFloorId, mRoomId, MainFragment.SCREEN_DEVICE,
	 * nameRoom, nameFloor); // mainFragment.setButtonToDevice(); }
	 * getSupportFragmentManager().beginTransaction() .replace(R.id.activity_main_content,
	 * mainFragment, "main") .commit(); } else { mainFragment .onlyRefreshData(mFloorId, mRoomId,
	 * nameRoom, nameFloor); if (isSceneFragment) { mainFragment.switchFragment(false);
	 * mainFragment.setButtonToScence(); } else { mainFragment.switchFragment(true);
	 * mainFragment.setButtonToDevice(); }
	 * 
	 * }
	 * 
	 * }
	 */

	@Override
	public void onFloorRoomClick(int floor_id, int room_id, String floor_name,
			String room_name) {
		LogUltis.i(TAG, "Floor id=[" + floor_id + " vs room_id=[" + room_id);
		mRoomId = room_id;
		mFloorId = floor_id;
		MainActivity.nameRoom = room_name;
		MainActivity.nameFloor = floor_name;
		FragmentManager fragmentManager = getSupportFragmentManager();
		MainFragment mainFragment = (MainFragment) fragmentManager
				.findFragmentByTag("main");
		if (mainFragment == null) {
			mainFragment = MainFragment.newInstance(floor_id, room_id,
					MainFragment.SCREEN_DEVICE, nameRoom, nameFloor);
			getSupportFragmentManager().beginTransaction()
					.replace(R.id.activity_main_content, mainFragment, "main")
					.commit();
		} else {
			mainFragment
					.onlyRefreshData(mFloorId, mRoomId, nameRoom, nameFloor);
			mainFragment.setTitleActionbar(room_name + "-" + floor_name);

		}
		getSlidingMenu().showContent(true);

	}

	/*
	 * private void switchMainFragment(boolean isFragmentDevice) { FragmentManager fragmentManager =
	 * getSupportFragmentManager(); MainFragment fragment = (MainFragment) fragmentManager
	 * .findFragmentByTag("main"); if (fragment == null) { MainFragment mainFragment =
	 * MainFragment.newInstance(mFloorId, mRoomId, MainFragment.SCREEN_DEVICE, nameRoom, nameFloor);
	 * getSupportFragmentManager().beginTransaction() .replace(R.id.activity_main_content,
	 * mainFragment, "main") .commit(); mainFragment.switchFragment(isFragmentDevice); } else {
	 * fragment.switchFragment(isFragmentDevice); } }
	 */
	// private void turnAllOffOnRoom(int room_id) {
	// FragmentManager fragmentManager = getSupportFragmentManager();
	// MainFragment fragment = (MainFragment) fragmentManager
	// .findFragmentByTag("main");
	// if (fragment != null) {
	// fragment.turnAllOffOnroom(room_id);
	// } else {
	// Toast.makeText(getApplicationContext(),
	// getString(R.string.txt_error), Toast.LENGTH_SHORT).show();
	// }
	// }
	//
	// private void turnAllOnOnRoom(int room_id) {
	// FragmentManager fragmentManager = getSupportFragmentManager();
	// MainFragment fragment = (MainFragment) fragmentManager
	// .findFragmentByTag("main");
	// if (fragment != null) {
	// fragment.turnAllOnOnRoom(room_id);
	// } else {
	// Toast.makeText(getApplicationContext(),
	// getString(R.string.txt_error), Toast.LENGTH_SHORT).show();
	// }
	// }

	// private void setTitleActionbar(String string) {
	//
	// /*
	// * Typeface TF = Typeface.createFromAsset(getApplication().getAssets(), LumiHome.font);
	// * getSupportActionBar().setTitleTypeface(TF); getSupportActionBar().setTitle(string);
	// */
	// titleActionbar.setText(string);
	//
	// }

	@Override
	public void onTabSelected(TABS tab) {
		if (tab == TABS.DEVICE) {
			mCurrentTab = TAB_DEVICE;
			// setButtonToDevice();
		} else if (tab == TABS.SCENE) {
			mCurrentTab = TAB_SCENE;
			// setButtonToScence();
		}

	}

	@Override
	protected void onPause() {
		if (isFinishing() == true) {
			getApplicationContext().getContentResolver().update(
					SmartHomeProvider.END_APPLICATION_URI, null, null, null);
			boolean stopservice = stopService(new Intent(
					getApplicationContext(), SmartHomeService.class));
			Log.d("Main Activity", "stopservice=" + String.valueOf(stopservice));
			ReceiveDataThread.End();
			TransmitThread.End();
		}
		super.onPause();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		getApplicationContext().getContentResolver().update(
				SmartHomeProvider.END_APPLICATION_URI, null, null, null);
		stopService(new Intent(getApplicationContext(), SmartHomeService.class));

		ReceiveDataThread.End();
		TransmitThread.End();
		Log.e("Destroy", "Destroy");

	}

	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub

		DialogLumi.showAlertDialogBoth(this, new DialogInterfaceLumi() {

			@Override
			public void OnClickOk() {
				// TODO Auto-generated method stub
				if (Config.isVibrate)
					new VibrateThread(getApplicationContext()).start();
				finish();
			}

			@Override
			public void OnClickCancel() {
				// TODO Auto-generated method stub
				if (Config.isVibrate)
					new VibrateThread(getApplicationContext()).start();
			}
		}, getString(R.string.txt_Announcement),
				getString(R.string.txt_Announcement_exit));
		if (Config.isVibrate)
			new VibrateThread(getApplicationContext()).start();
	}

	@Override
	public void settingOnListener() {
		// TODO Auto-generated method stub
		FragmentManager fragmentManager = getSupportFragmentManager();
		MenuFragment menuFragment = (MenuFragment) fragmentManager
				.findFragmentByTag("menu");
		if (menuFragment == null) {
			FragmentTransaction transaction = fragmentManager
					.beginTransaction();
			transaction.replace(R.id.activity_main_menu_content, menuFragment,
					"menu").commit();
		}
		menuFragment.changeLanguage();
	}

}
